import { useEffect } from 'react';
import { queryNewsLatestApi, queryNewsBeforeApi } from '@/api/index';
import { useState } from 'react';
import { Swiper, DotLoading } from 'antd-mobile';
import HomeWrapper from './style';
import Article from '@/components/Article';
import useScrollbottom from '@/hooks/useScrollBottom.js';
import HomeHead from './HomeHead';

const Home = () => {
  const [banners, setBanners] = useState([]),
    [news, setNews] = useState([]),
    [dotLoading, setDotLoading] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const { date, stories, top_stories } = await queryNewsLatestApi();
        setBanners([...top_stories]);
        setNews([...news, { date, list: stories }]);
      } catch (_) {}
    })();
  }, []);

  const isBottom = useScrollbottom();
  // 监听页面滚动到底部
  useEffect(() => {
    if (isBottom) {
      (async () => {
        try {
          setDotLoading(true);
          const { date, stories } = await queryNewsBeforeApi(news[news.length - 1].date);
          setNews([...news, { date, list: stories }]);
          setDotLoading(false);
        } catch (_) {}
      })();
    }
  }, [isBottom]);

  return (
    <HomeWrapper>
      <HomeHead />
      {/* 轮播图 */}
      <div className="swiper-box">
        {!!banners.length && (
          <Swiper autoplay loop infinite dots vertical>
            {banners.map((banner) => {
              const { id, image, title, hint } = banner;
              return (
                <Swiper.Item className="swiper-item" key={id}>
                  <img className="banner-img" src={image} alt={title} />
                  <div className="desc-box">
                    <div className="desc-text">{title}</div>
                    <div className="desc-author">{hint}</div>
                  </div>
                </Swiper.Item>
              );
            })}
          </Swiper>
        )}
      </div>
      {/* 新闻列表 */}
      {!!news.length && news.map((item, index) => <Article key={index} item={item} index={index} />)}
      {/* 加载更多 */}
      <div className="more" style={{ display: dotLoading ? 'block' : 'none' }}>
        <span>数据加载中</span>
        <DotLoading color="currentColor" />
      </div>
    </HomeWrapper>
  );
};

export default Home;
